<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img v-if="avatar" :src="avatar" alt="" class="preview" />
      <img v-else src="../../../assets/images/avatar.jpg" alt="" class="preview" />

      <!-- 文件选择框 -->
      <input type="file" accept="image/*" hidden ref="inputFile" @change="cImage">

      <!-- 按钮区域 -->
      <div class="btn-box">
        <el-button type="primary" icon="el-icon-plus" @click="oImage">选择图片</el-button>
        <el-button type="success" icon="el-icon-upload" :disabled="avatar === ''" @click="uploadAvatar">上传头像</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserAvatar',
  data(){
    return{
      avatar:''
    }
  },
  methods:{
    oImage(){
      this.$refs.inputFile.click()
    },
    cImage(e){
      // console.log(111)
      const file = e.target.files
      if(file.length === 0){
        this.avatar = ''
      } else{
        const fr = new FileReader()
        fr.readAsDataURL(file[0])
        // fr.onload= e =>{
        //   this.avatar = e.target.result
        // }
        fr.addEventListener('load',()=>{
          this.avatar=fr.result
        })
      }
    },
    async uploadAvatar(){
      const {data:res} = await this.$http.patch('/my/update/avatar',{avatar:this.avatar})
      // 上传头像失败
      if(res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      // 通知vuex,触发actions里面的函数
      this.$store.dispatch('getUserInfo')
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
  width: 350px;
  height: 350px;
}
</style>
